<template>
  <div class="login_views">
     <img class="logo" :src="'./images/logo2.png'" /> 
      <div class="left_form">
        <div>
          <h2>登录</h2>
          <el-form class="forms"  
            ref="ruleFormRef"
            :hide-required-asterisk="true"
            :model="loginForm"
            :rules="loginRules">
          <el-form-item label="" prop="username"> 
            <el-input placeholder="请输入用户名" v-model="loginForm.username" />
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input  placeholder="请输入密码" v-model="loginForm.password" type="password" />
          </el-form-item> 
          <el-button class="submit_btn" @click="submitForm(ruleFormRef)">登录</el-button>
        </el-form> 
        </div>
      </div> 
  </div>  
</template>
<script lang="ts">
import './index.scss' 
import { defineComponent, ref, reactive, toRefs, onMounted, } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { fetch }  from '@/utils/request'
import {  messagePopup } from '@/utils/util'
import { commonStroe } from '@/stores/common'
import { useRouter, useRoute } from 'vue-router'
import { encrypt } from '@/utils/jsencrypt'

export default defineComponent({
  setup() { 
    const router = useRouter()
    const stroe = commonStroe() 
    
    const ruleFormRef = ref<FormInstance>()
    const dataMap = reactive({
      loginForm: {
        username: '',
        password: ''
      },
     loginRules: {
        username: [{ trigger: 'change', required: true, message: '请输入用户名' }],
        password: [{ trigger: 'change', required: true, message: '请输入密码' }]
      },
    }) 
  
    const methods = reactive({
      submitForm: (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.validate((valid) => {
          if (valid) {
            methods.requestLogin()
            console.log('submit!')
          } else {
            console.log('error submit!')
            return false
          }
        })
      },
      
      /**
       * 登录请求
       */
      requestLogin: () => {
        let { username, password } = dataMap.loginForm 
        const params = { 
           username: encrypt(username),
          password: encrypt(password), 
          grant_type: 'password',
        }
        fetch('fetchLogin', params, (data: any) => {
          const result = data.datas
          if (result) {   
            sessionStorage.setItem('fullName', result.login_user_name)
            sessionStorage.setItem('userId', result.login_user_id)   
            stroe.setLoginState(true)   
            stroe.setToken(result.access_token) 
            router.push('/index')
            // 在 Vue 实例中 
          } else {
            messagePopup(data.error || '登录失败', 'error')
          }
        })
      }
    }) 
 
    return {
      ruleFormRef,
      ...toRefs(dataMap),
      ...toRefs(methods)
    }
  },
})
</script>
